import React, { useCallback, useEffect, useState } from "react";
import { Modal, Button, Space, Image } from "antd";
import { SearchCheckboxTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import PickAssignmentModal from "./component/PickAssignmentModal";
import StockLockInModal from "./component/StockLockInModal";
import UpdateLogListModal from "./component/UpdateLogListModal";
import { useNavigate } from "react-router-dom";
import { Input, Select, BatchSuffixInput } from "@/views/components/PrefixPlaceholder";
import { getInventoryList, inventorySum, getWarehouseList } from "./service";
import { NumText } from "@/pages/OrderModule/common/components/CommonText";
import ActionExportExcelModal from "./component/ActionExportExcelModal"; // 导出弹窗
import { isEmpty } from "lodash";
import styles from "./component/index.module.less";
const SeparateStock = () => {
	const [visible, setVisible] = useState(0); //快销采购弹窗
	const navigate = useNavigate();
	const [selectedWarehouse, setSelectedWarehouse] = useState("");
	const [data, setData] = useState(null);
	const [record, setRecord] = useState(null);
	const [warehouseList, setWarehouseList] = useState([]);
	const [defaultValue, setDefaultValue] = useState(null);
	const tableRequest = getInventoryList;

	const [footerDataSource, setFooterDataSource] = useState([
		{
			skuId: "footerDataSource",
			actualNum: 0,
			defectiveNum: 0,
			wayNum: 0,
			totalPrice: 0,
			children: null
		}
	]);
	const defaultColumns = [
		{
			name: "商品图片",
			code: "skuImage",
			render: (value, record, i) => {
				if (record.skuId == "footerDataSource") return "合计";
				return <Image width={60} src={value} />;
			},
			search: {
				order: 11,
				code: "warehouseId",
				formItemProps: {
					initialValue: defaultValue
				},
				content: () => (
					<Select placeholder="仓库" onChange={handleWarehouseChange}>
						{options}
					</Select>
				)
			},

			width: 200
		},
		{
			name: "商品名称",
			code: "skuName",
			search: {
				order: 2,
				content: () => <Input allowClear placeholder="商品名称" />
			},
			width: 200
		},
		{
			name: "商品编码",
			code: "skuCode",
			search: {
				order: 2,
				content: () => <Input placeholder="商品编码" />
			},
			width: 200
		},
		{
			name: "款式编码",
			code: "spuCode",
			search: {
				order: 2,
				content: () => <Input placeholder="款式编码" />
			},
			width: 200
		},
		{
			name: "颜色规格",
			code: "skuSpec",
			search: {
				order: 2,
				content: () => <Input placeholder="颜色规格" />
			},
			width: 200
		},
		{
			name: "正品实际库存",
			code: "actualNum",
			render: (value, record, i) => (
				<div>
					<div>{value}</div>
					{value && (
						<div>
							{record.price && (
								<NumText as="s1" pre="¥" num={value * record.price ? (value * record.price).toFixed(2) : 0}></NumText>
							)}
						</div>
					)}
				</div>
			),
			width: 200
		},
		{
			name: "低预警值",
			code: "lowWarnValue",
			width: 200,
			search: {
				order: 2,
				code: "warnType",
				content: () => (
					<Select
						allowClear
						placeholder="预警"
						options={[
							{
								value: 1,
								label: "红色预警"
							},
							{
								value: 2,
								label: "黄色预警"
							}
						]}
					/>
				)
			}
		},
		{
			name: "高预警值",
			code: "highWarnValue",
			width: 200
		},
		{
			name: "正品可售数",
			code: "saleableNum",
			width: 200
		},
		{
			name: "销售锁定数",
			code: "lockedNum",
			render: (text, record) => (
				<span className="opera-span-common">
					<span className="common-color2" onClick={() => commonHandleClick(5, record)}>
						{text}
					</span>
				</span>
			),
			width: 200
		},
		{
			name: "次品实际库存",
			code: "defectiveNum",
			render: (value, record, i) => (
				<div>
					<div>{value}</div>
					{value && (
						<div>
							{value && (
								<div>
									{record.price && (
										<NumText as="s1" pre="¥" num={value * record.price ? (value * record.price).toFixed(2) : 0}></NumText>
									)}
								</div>
							)}
						</div>
					)}
				</div>
			),
			width: 200
		},
		{
			name: "总库存数",
			code: "totalNum",
			width: 200
		},
		{
			name: "总库存金额（元）",
			code: "totalPrice",
			width: 200,
			render: value =>
				value && <NumText as="s1" pre="¥" style={{ color: "rgba(240, 61, 41, 1)" }} num={value ? value.toFixed(2) : 0} />
		},
		{
			name: "采购在途数",
			code: "wayNum",
			width: 200
		},
		{
			name: "操作",
			code: "action",
			lock: true,
			width: 200,

			render: (t, r, i) => {
				if (r.skuId == "footerDataSource") return "";
				return (
					<span className="opera-span-common">
						<span className="common-color2" onClick={() => commonHandleClick(6, r)}>
							修改日志
						</span>
						<i>|</i>
						<span onClick={() => handleJump(r)}>出入库记录</span>
					</span>
				);
			}
		}
	];
	const options =
		!isEmpty(warehouseList) &&
		warehouseList.map(item => (
			<Option value={item.id} key={item.id}>
				{item.warehouseName}
			</Option>
		));
	const handleJump = record => {
		const { skuCode, warehouseId } = record;
		navigate("/views/stock/AccessRecords", { state: { warehouseId, goodsCode: skuCode } });
	};
	const [columns, setColumns] = useState(defaultColumns);
	useEffect(() => {
		if (defaultValue) {
			setColumns(defaultColumns);
		}
	}, [defaultValue]);
	const getFmcgpurchasesCountListFn = async () => {
		const totalwayNum = dataSource.reduce((sum, item) => sum + Number(item.wayNum), 0);
		const totalDefectiveNum = dataSource.reduce((sum, item) => sum + Number(item.defectiveNum), 0);
		const totalActualNum = dataSource.reduce((sum, item) => sum + Number(item.actualNum), 0);
		const totalTotalPrice = dataSource.reduce((sum, item) => sum + Number(item.totalPrice), 0);
		setFooterDataSource(pre => {
			return [
				{
					...pre[0],
					wayNum: totalwayNum ? totalwayNum : 0,
					defectiveNum: totalDefectiveNum ? totalDefectiveNum : 0,
					actualNum: totalActualNum ? totalActualNum : 0,
					totalPrice: totalTotalPrice ? totalTotalPrice : 0
				}
			];
		});
	};

	const rowKey = "id";
	const tableKey = "SeparateStock2123";
	const {
		form,
		selectedKeys,
		selectedRows,
		fetchList,
		dataSource,
		query,
		pagination,
		updateDataSource,
		updateSearchQuery,
		updatePaginationParams,
		searchSimpleTableProps
	} = useTableConfig({
		tableKey,
		rowKey,
		columns,
		tableRequest,
		autoFetch: false,
		hasPagination: true,
		hasQuickSearch: true,
		beforeQuerySearch: false,
		// footerDataSource,
		resetSourceData: false,
		columnResize: true,
		hasColsSetting: true
	});

	const commonHandleClick = (status, record) => {
		if (selectedRows.length || record) {
			setVisible(status);
			setRecord(record);
		} else {
			Modal.info({ centered: true, content: "请先勾选商品进行操作" });
		}
	};
	const getWarehouseFunc = async () => {
		const { data = [], success } = await getWarehouseList(); // 假设getWarehouseList是一个获取仓库列表的异步函数
		if (success) {
			if (data.length > 0) {
				setWarehouseList(data);
				const warehouseId = data[0].id;
				setDefaultValue(warehouseId);
				fetchList({ warehouseId });
				form.setFieldValue("warehouseId", warehouseId);
			}
		}
	};
	const handleWarehouseChange = async value => {
		setSelectedWarehouse(value);
		fetchList({ warehouseId: value });
		const { data, success } = await inventorySum({ warehouseId: value });
		if (success) {
			setData(data);
		}
	};
	const exportExcel = () => {
		setVisible("ProgressModal");
	};
	const leftBtns = (
		<Space>
			<Button style={{ marginRight: "8px" }} onClick={() => commonHandleClick(1)}>
				正品盘点
			</Button>
			<Button style={{ marginRight: "8px" }} onClick={() => commonHandleClick(2)}>
				次品盘点
			</Button>
			<Button style={{ marginRight: "8px" }} onClick={() => commonHandleClick(3)}>
				增加库存
			</Button>
			<Button style={{ marginRight: "8px" }} onClick={() => commonHandleClick(4)}>
				设置预警值
			</Button>
			<Button onClick={exportExcel} style={{ marginRight: "8px" }}>
				表格导出
			</Button>
			<div>
				库存总金额：<span style={{ color: "rgba(240, 61, 41, 1)" }}>￥{data ? data : 0}</span>
			</div>
		</Space>
	);

	const CheckSeparateStockProps = {
		visible,
		selectedRows,
		selectedKeys,
		fetchList,
		selectedWarehouse,
		record,
		handleOk() {},
		handleCancel() {
			setVisible(0);
		}
	};
	// const realProps = {
	// 	createTaskData: {
	// 		businessParam: JSON.stringify({
	// 			ids: dataSource.map(e => e.id),
	// 			businessKey: 3
	// 		}),
	// 		taskType: 4003
	// 	},
	const searchData = form.getFieldsValue();
	const realProps = {
		createTaskData: {
			businessParam: JSON.stringify({
				searchData,
				current: pagination.current, // 当前页
				size: pagination.pageSize, // 每页的数量
				businessKey: 3
			}),
			taskType: 4003
		},
		onCancel() {
			setVisible("");
		}
	};
	useEffect(() => {
		getFmcgpurchasesCountListFn();
	}, [dataSource]);

	useEffect(() => {
		getWarehouseFunc();
	}, []);
	return (
		<div className={styles.tableTotal + " nihao"}>
			<SearchCheckboxTable key={tableKey} leftBtns={leftBtns} {...searchSimpleTableProps} />
			{(visible == 1 || visible == 2 || visible == 3 || visible == 4) && <PickAssignmentModal {...CheckSeparateStockProps} />}
			{visible == 5 && <StockLockInModal {...CheckSeparateStockProps} />}
			{visible == 6 && <UpdateLogListModal {...CheckSeparateStockProps} />}
			{visible == "ProgressModal" && <ActionExportExcelModal {...realProps} />}
		</div>
	);
};

export default React.memo(SeparateStock, () => {
	return true;
});
